package uk.co.cocking.getinline2.restlet;

import java.util.ArrayList;
import java.util.List;

import org.restlet.Component;
import org.restlet.Restlet;
import org.restlet.data.Protocol;

import uk.co.cocking.getinline2.exceptions.EnvironmentException;
import uk.co.cocking.getinline2.pipeline.Consumer;


public class RestfulServer {
	private Component component = new Component();
	private List<Consumer<String>> pipelines = new ArrayList<Consumer<String>>();
	
	public void run() throws Exception {
		component.start();
	}

	public RestfulServer(int port) {
        component.getServers().add(Protocol.HTTP, port);
		attach("/shutdown", new ShutdownRestlet(this));
	}

	private void attach(String urlPattern,
			Restlet restlet) {
		component.getDefaultHost().attach(urlPattern, restlet);
	}

	public void attachConsumer(String baseUrl, Consumer<String> pipeline) throws EnvironmentException {
		attach(baseUrl, new StringForwardingRestlet(pipeline));
		pipelines.add(pipeline);
		pipeline.open();
	}

	public void stop() throws EnvironmentException {
		for (Consumer<String> pipeline: pipelines) {
			pipeline.close();
		}
	}
	
	

}
